package com.aiyige.page.my.order.sellerOrder;


import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.eventbus.EventBuySuccess;
import com.aiyige.base.eventbus.EventOrderScreen;
import com.aiyige.base.eventbus.EventRefundAgree;
import com.aiyige.base.eventbus.EventRefundReject;
import com.aiyige.model.OrderEntity;
import com.aiyige.model.eshop.Order;
import com.aiyige.model.request.OrderListForSellerRequest;
import com.aiyige.model.response.OrderListResponse;
import com.aiyige.page.my.order.adapter.OrderListAdapter;
import com.aiyige.page.my.order.model.ScreenEntity;
import com.aiyige.page.my.order.model.SubjectSelection;
import com.aiyige.utils.ListUtil;
import com.aiyige.base.BaseFragment;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;

public class OrderDataPage extends BaseFragment implements CommonDataView.RetrofitStub {

    public static final int TYPE_All_PAGE_1 = 1;// 全部
    public static final int TYPE_WAITING_PAY_PAGE_2 = 2;// 待付款
    public static final int TYPE_WAITING_SERVICE_PAGE_3 = 3;// 待服务/发货
    public static final int TYPE_WAITING_AFFIRM_PAGE_4 = 4;// 待确认
    public static final int TYPE_AFTER_SALE_PAGE_5 = 5;// 退款/售后

    private int pageType = -1;
    @BindView(R.id.cdv)
    CommonDataView cdv;
    OrderListAdapter adapter;

    ScreenEntity screenEntity;

    public OrderDataPage() {
    }

    public String getPageTitle() {
        switch (pageType) {
            case TYPE_All_PAGE_1:
                return MyApp.getAppContext().getString(R.string.all);
            case TYPE_WAITING_PAY_PAGE_2:
                return MyApp.getAppContext().getString(R.string.waiting_pay_page);
            case TYPE_WAITING_SERVICE_PAGE_3:
                return MyApp.getAppContext().getString(R.string.waiting_service_page);
            case TYPE_WAITING_AFFIRM_PAGE_4:
                return MyApp.getAppContext().getString(R.string.waiting_affirm_page);
            case TYPE_AFTER_SALE_PAGE_5:
                return MyApp.getAppContext().getString(R.string.waiting_after_sale_page);
            default:
                return "";
        }
    }

    public int getPageType() {
        return pageType;
    }

    public void setPageType(int pageType) {
        this.pageType = pageType;
    }

    public static OrderDataPage newInstance(int pageType) {
        OrderDataPage fragment = new OrderDataPage();
        fragment.setAutoRegisterEventBus(true);
        fragment.setPageType(pageType);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_order_manager_data, container, false);
        ButterKnife.bind(this, view);
        adapter = new OrderListAdapter();
        adapter.setBuyer(false);
        adapter.setHideTypeLayout(true);
        cdv.config(adapter, this);
        cdv.addItemDecoration(6, R.color.zwcolor_gray_f4f8f9);
        cdv.setRecyclerViewBgColor(ContextCompat.getColor(getActivity(), R.color.zwcolor_gray_f4f8f9));
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                OrderEntity orderEntity = (OrderEntity) adapter.getData().get(position);
                ARouter.getInstance().build(ARouterConfig.OrderDetailPage).withString("orderId", orderEntity.getOrderId()).withBoolean("isBuyer",false).navigation();
//                if (orderEntity.getStatus() == OrderEntity.STATUS_0_NOPAY) {
//                    ARouter.getInstance().build(ARouterConfig.OrderManagerDetailNoPayPage).withString("orderId", orderEntity.getOrderId()).navigation();
//                }
//                if (orderEntity.getStatus() == OrderEntity.STATUS_1_PAYED || orderEntity.getStatus() == OrderEntity.STATUS_3_WAITING_SHIP) {
//                    ARouter.getInstance().build(ARouterConfig.OrderManagerDetailfinishPage).withString("orderId", orderEntity.getOrderId()).navigation();
//                }
//                if (orderEntity.getStatus() == OrderEntity.STATUS_2_CANCEL) {
////                    ARouter.getInstance().build(ARouterConfig.OrderManagerDetailfinishPage).withString("orderId", orderEntity.getOrderId()).navigation();
//                    ARouter.getInstance().build(ARouterConfig.OrderManagerDetailNoPayPage).withString("orderId", orderEntity.getOrderId()).navigation();
//                }
//                case 2:

//                break;

            }
        });
        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventOrderScreen(EventOrderScreen event) {
        screenEntity = event.screenEntity;
        cdv.refresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefundAgree(EventRefundAgree eventRefundAgree) {
        if (cdv != null) {
            cdv.refresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefundReject(EventRefundReject eventRefundReject) {
        if (cdv != null) {
            cdv.refresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPaySuccessEventBuss(EventBuySuccess eventBuySuccess) {
        if (cdv != null) {
            cdv.refresh();
        }
    }

    private String getTime() {
        return screenEntity != null ? screenEntity.getTime() : "";
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {

        switch (pageType) {
            case TYPE_All_PAGE_1:
                return OrderListForSellerRequest.newBuilder()
                        .pageNum(currentPage)
                        .subject(getSubjects())
                        .uiStatus(Order.Range.ALL)
                        .timePeriod(getTime())
                        .build();
            case TYPE_WAITING_PAY_PAGE_2:
                return OrderListForSellerRequest.newBuilder()
                        .pageNum(currentPage)
                        .subject(getSubjects())
                        .uiStatus(Order.Range.NOPAY)
                        .build();
            case TYPE_WAITING_SERVICE_PAGE_3:
                return OrderListForSellerRequest.newBuilder()
                        .pageNum(currentPage)
                        .subject(getSubjects())
                        .uiStatus(Order.Range.NOSHIP)
                        .timePeriod(getTime())
                        .build();
            case TYPE_WAITING_AFFIRM_PAGE_4:
                return OrderListForSellerRequest.newBuilder()
                        .pageNum(currentPage)
                        .subject(getSubjects())
                        .uiStatus(Order.Range.UNCONFIRM)
                        .timePeriod(getTime())
                        .build();
            case TYPE_AFTER_SALE_PAGE_5:
                return OrderListForSellerRequest.newBuilder()
                        .pageNum(currentPage)
                        .subject(getSubjects())
                        .uiStatus(Order.Range.AFTERSALE)
                        .timePeriod(getTime())
                        .build();
            default:
                return OrderListForSellerRequest.newBuilder()
                        .pageNum(currentPage)
                        .subject(getSubjects())
                        .uiStatus(Order.Range.ALL)
                        .timePeriod(getTime())
                        .build();
        }
    }

    private List<String> getSubjects() {
        if (screenEntity != null && screenEntity.getTypes() != null
                && !screenEntity.getTypes().isEmpty()) {
            List<String> types = new ArrayList<>();
            for (SubjectSelection subjectSelection : screenEntity.getTypes()) {
                types.add(subjectSelection.getSubject());
            }
            return types;
        }
        return null;
    }

    private List<OrderEntity> orderListToOrderEntityList(List<Order> list) {
        List<OrderEntity> orderEntityList = new ArrayList<>();
        if (!ListUtil.isEmpty(list)) {
            for (Order order : list) {
                orderEntityList.add(new OrderEntity(order));
            }
        }
        return orderEntityList;
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            OrderListResponse homeResponse = JSON.parseObject(respJson, OrderListResponse.class);
            if (homeResponse == null) {
                throw new Exception(homeResponse.getMessage());
            } else {
                resultList.addAll(orderListToOrderEntityList(homeResponse.getContent()));
                return new CommonDataView.HandleResult(homeResponse.isLast());
            }
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }

    }

    @Override
    protected void initData() {
        cdv.doRefreshRequest();
    }
}
